package cn.tedu.boot22.controller;

import cn.tedu.boot22.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@Controller
public class EmpController {
    @RequestMapping("/select")
    @ResponseBody
    public String select(){
        String html="<table border=1>";
        html+="<caption>员工列表</caption>";
        html+="<tr><td>id</th><th>名字</th><th>工资</th></tr>";
        //此处写查询数据库的代码
        try (Connection conn= DBUtils.getConn()){
            String sql="select id,name,sal from emp";
            //SQl语句中没有变量 可以使用Statement或preparedStatement
            Statement s=conn.createStatement();
            //执行查询
            ResultSet rs=s.executeQuery(sql);
            //遍历查询结果
            while (rs.next()){
                int id=rs.getInt(1);
                String name=rs.getString(2);
                int sal=rs.getInt(3);
                html+="<tr>";
                html+="<td>"+id+"</td>";
                html+="<td>"+name+"</td>";
                html+="<td>"+sal+"</td>";
                html+="</tr>";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        html+="</table>";
        return html;
    }
}
